#include<stdio.h>
#include <assert.h> 
#include <pthread.h> 
#include <unistd.h>
#include<stdlib.h>
#include "defs.h"

typedef struct 
{
    int i;
    int m;
    int gap;
    double *a;
    double *b;
    double *c;
}arr; 

void *mythread(void *pt) { 
    arr tmp = *(arr*)pt;
    double *a = tmp.a;double *b = tmp.b;double *c = tmp.c;
    int i, j, p;
    int m ,n ,k;
    m = n = k =tmp.m;
    i = tmp.i;
    int num = i + tmp.gap;

  for (; i < num; i++) /* Loop over the rows of C */
  {
    for (j = 0; j < n; j++) /* Loop over the columns of C */
    {
      for (p = 0; p < k; p++)
      { /* Update C( i,j ) with the inner product of the ith row of A and the jth column of B */
        c[i*m+j] += a[i*m+p] * b[p*m+j];
      }
    }
  }
    
    return NULL; 
} 



void MY_MMult(int m, int n, int k, double *a, int lda,
              double *b, int ldb,
              double *c, int ldc)
{
    int size = 8;
    int gap = m / size; int i = 0; int rc;int num = 0;
    pthread_t p[size];
    arr index[size];

    for(i = 0 ;i < size ;i ++)
    {
      index[i].a = a;
      index[i].b = b;
      index[i].c = c;
      index[i].m = m;
      index[i].gap = gap;
    }
    
    for(i = 0;i < m ;i +=gap)
    {
        index[num].i = i;
        rc = pthread_create(&p[num], NULL, mythread, &index[num]); assert(rc == 0); 
        num ++;
    }

    for(num = 0;num < size;num ++)
    {
        rc = pthread_join(p[num], NULL); assert(rc == 0); 
    }
  

}
